//
//  BBAppController.m
//  xNose
//
//  Created by ben smith on 9/7/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "BBAppController.h"
#import "BBNodeController.h"
#import "BBLibraryController.h"


@implementation BBAppController

@synthesize dispatchDelegate;
@synthesize oscListener;
@synthesize currentTouchPosition;

BBAppController * sharedAppController;

-(void)awakeFromNib
{
	// setup my singlton values
	sharedAppController = self;
	// hook up to the nsapp
	[NSApp setDelegate:self];
}

+(BBAppController*)sharedAppController
{
	//return the singleton
	return sharedAppController;
}

-(void)setCurrentTouchPosition:(NSPoint)p
{
	currentTouchPosition = p;
//	NSLog(@"set the MF: %@",NSStringFromPoint(p));
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
	// just started up, load up the last saved project
	NSString * dir = [self applicationSupportFolder];
	if ([[NSFileManager defaultManager] fileExistsAtPath:[dir stringByAppendingPathComponent:@"default.xnp"] isDirectory:NULL]) {
		[self loadFromFile:[dir stringByAppendingPathComponent:@"default.xnp"]];
	}	else {
		[self loadFromFile:[dir stringByAppendingPathComponent:@"default.xNoderProj"]];		
	}
	if ([[NSUserDefaults standardUserDefaults] boolForKey:@"BBLaunchInFullscreen"])
		[fullscreenController toggleFullScreen:self];
	[self performSelector:@selector(connect) withObject:nil afterDelay:1.0];
}

-(void)connect
{
	BBTUIODispatchDelegate * newDelegate = [[BBTUIODispatchDelegate alloc] init];
	self.dispatchDelegate = newDelegate;
	[newDelegate release];
	
	// make a new listener, point it at the specified port
	// and hook it up to the dispatch delegate
	
	BBOSCListener * newListener = [[BBOSCListener alloc] init];

	[newListener setDelegate:self.dispatchDelegate];
	[newListener startListeningOnPort:3333];
	// keep a copy for myself
	self.oscListener = newListener;
	
	// clean up
	[newListener release];
}

-(IBAction)launchOther:(id)sender
{
//	[self.oscListener stopListening];
	
	NSString * otherApp = [[NSUserDefaults standardUserDefaults] objectForKey:@"BBExternalAppLocation"];
	if (otherApp != nil) {
		if ([[NSWorkspace sharedWorkspace] launchApplication:otherApp]) {
			NSLog(@"woot?");
		}			
	}
	[NSApp terminate:self];
}


-(IBAction)commandOne:(id)sender
{
	NSString * filename = [[NSUserDefaults standardUserDefaults] objectForKey:@"BBScene1FileName"];
	if (![[NSFileManager defaultManager] fileExistsAtPath:filename isDirectory:NO]) return;
	[self loadFromFile:filename];
}

-(NSPoint)currentTouchPosition
{
	
}

-(void)loadFromFile:(NSString*)filename
{
	// load up form a specified filename
	// decode the two main objects
	// tree at 0
	// library at 1
	[[BBNodeController sharedNodeController] setScale:1.0];
	NSArray * nodes = [NSKeyedUnarchiver unarchiveObjectWithFile:filename];
	if ([nodes objectAtIndex:0] != nil) {
		[[BBNodeController sharedNodeController] setRootNode:[nodes objectAtIndex:0]];		
	}
	
	// clear out any lingering objects in the library, otherwise it gets messy
	[[BBLibraryController sharedLibraryController] clearLibrary];
	[[[BBLibraryController sharedLibraryController] libraryNodes] addObjectsFromArray:[nodes objectAtIndex:1]];
	// if there were no library objects, add the default primitives
	if ([[[BBLibraryController sharedLibraryController] libraryNodes] count] == 0) [[BBLibraryController sharedLibraryController] makeDefaultLibrary];

	// setup the main view
	[[BBNodeController sharedNodeController] refreshView:nil];
}
	
-(void)saveToFile:(NSString*)filename
{
	// stuff the two main objects into a nice array
	NSArray * nodes = [NSArray arrayWithObjects:[[BBNodeController sharedNodeController] rootNode],[[BBLibraryController sharedLibraryController] libraryNodes],nil];
	
	// find out if we have the right suffix, if not add it
	NSString * ultimatFileName = filename;
	if (![filename hasSuffix:@".xnp"]) {
		ultimatFileName = [ultimatFileName stringByAppendingPathExtension:@"xnp"];
	}
	
	// archive baby!
	BOOL result = [NSKeyedArchiver archiveRootObject:nodes toFile:ultimatFileName];
	
	// TODO: make this nicer
	if (!result)
		[[NSAlert alertWithMessageText:@"Cannot save file!" defaultButton:@"Oh, ok." alternateButton:nil otherButton:nil informativeTextWithFormat:@"There was an error saving to the file: %@",ultimatFileName] runModal];	
}

-(IBAction)newProject:(id)sender
{
	// just clear out all the various objects and refresh the view
	[[BBNodeController sharedNodeController] newTree];
	[[BBLibraryController sharedLibraryController] makeDefaultLibrary];
	[[BBNodeController sharedNodeController] refreshView:self];
}

-(IBAction)saveProjectToFile:(id)sender
{
	// standard save panel
	NSSavePanel *sp;
	int runResult;
	
	sp = [NSSavePanel savePanel];
		
	runResult = [sp runModalForDirectory:NSHomeDirectory() file:@""];
	
	if (runResult == NSOKButton) {
		[self saveToFile:[sp filename]];
 	}
}

-(IBAction)loadProject:(id)sender
{
	// standard open panel
	int result;
	NSOpenPanel *oPanel = [NSOpenPanel openPanel];
	
	[oPanel setAllowsMultipleSelection:NO];
	result = [oPanel runModalForDirectory:NSHomeDirectory()
																	 file:nil types:nil];
	if (result == NSOKButton) {
		NSArray *filesToOpen = [oPanel filenames];
		NSString *aFile = [filesToOpen objectAtIndex:0];
		[self loadFromFile:aFile];
	}
	
}

-(IBAction)resetNodeTree:(id)sender
{
	// this will generate a simple test node tree that i harcoded
	[[BBNodeController sharedNodeController] makeDefaultNodeTree];
	[[BBNodeController sharedNodeController] refreshView:nil];
}

- (void)applicationWillTerminate:(NSNotification *)aNotification
{
	// save off what we are doing
	NSString * dir = [self applicationSupportFolder];
	[self saveToFile:[dir stringByAppendingPathComponent:@"default.xnp"]];
	// launch the other app
}

-(NSString*)applicationSupportFolder 
{	
	// this just returns the named folder that is in ~/Library/Application Support
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
	NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
	// got the app support directory, now check to make sure there is a folder for us
	//TODO: change this to xNoder
	NSString * dir = [basePath stringByAppendingPathComponent:@"xNose"];
	if (![[NSFileManager defaultManager] fileExistsAtPath:dir isDirectory:NULL]) {
		[[NSFileManager defaultManager] createDirectoryAtPath:dir attributes:nil];
	}	
	return dir;
}
@end
